<template>
  <div class="orderChangeDetails h100">
    <editPageNew
      ref="editPage"
      :stepConfig="stepConfig"
      :rightBtnArr="rightBtnArr"
      :moreBtnArr="moreBtnArr"
      showStep
      showTopTitle
      :showMore="showMore"
      :creatInfo="formData"
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        工单变更单 {{formData.code}}
      </template>
      <div class="orderTitle">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span class="titleText" :title="orderTitle">{{ orderTitle }}</span>
          <el-link
            v-show="showBaseBtn"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input" :class="{remindColor:!userInput}">
          <el-input
            type="text"
            v-model="orderTitle"
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
          >
            <template slot="prepend">标题</template>
          </el-input>
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">变更信息</template>
          <editForm :formConfig="editFormConfig" ref="basicForm" :formData="formData">
            <!-- 工单选择 -->
            <template #orderCode="{editFormInfo}">
              <el-input
                v-model="editFormInfo.orderCode"
                size="mini"
                class="input-with-select input-link"
                readonly
                :disabled="disabled"
                placeholder="请选择工单"
                @click.native="goToDetails()"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  :disabled="disabled"
                  @click.stop="() => showWorkOrder = true"
                ></el-button>
              </el-input>
            </template>
          </editForm>
          <dispatch
            v-if="showDispatch"
            ref="dispatch"
            :formData="selectOrder"
            :orderType="orderType"
            :onlyShow="disabled"
            useType="orderChange"
            :needGetData="isGetInfo"
            :changeData="dispatchChangeData"
            @changeData="changeData"
            @setDispatchData="setDispatchData"
          />
        </el-collapse-item>
        <el-collapse-item name="2" v-if="showDispatch">
          <template slot="title">工单基本信息</template>
          <defectForm
            ref="defect"
            :initData="formData"
            :orderStatus="status"
            :oldMajor="oldMajor"
            :pageType="pageType"
            v-if="orderType=='defect'"
          ></defectForm>
          <normalForm
            ref="normal"
            :initData="formData"
            :orderStatus="status"
            :menuType="orderType"
            :oldMajor="oldMajor"
            :pageType="pageType"
            v-if="showNormal"
          ></normalForm>
          <overhaulForm
            ref="overhaul"
            :initData="formData"
            :orderStatus="status"
            :oldMajor="oldMajor"
            :pageType="pageType"
            v-if="orderType=='overhaul'"
          ></overhaulForm>
        </el-collapse-item>
        <el-collapse-item name="3" v-if="showDispatch">
          <template slot="title">工单派工信息</template>
          <dispatch
            v-if="showDispatch"
            :formData="selectOrder"
            :orderType="orderType"
            useType="orderChange"
            onlyShow
            :needGetData="status!='DONE'"
            :changeData="dispatchChangeData"
            @changeData="changeData"
            @setDispatchData="setDispatchData"
          />
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <!-- 选择关联工单 -->
    <dialogPublic
      :title="'选择关联工单'"
      :show.sync="showWorkOrder"
      @doSubmit="selectOrders"
      @doClose="() => (showWorkOrder = false)"
      appendTobody
      fullscreen
    >
      <workorder ref="defectOrders" v-if="showWorkOrder"></workorder>
    </dialogPublic>
  </div>
</template>

<script>
import workorder from "@/views/orderManagement/orderChange/orderList";
import dispatch from "@/views/orderManagement/publicModule/dispatch";
import defectForm from "@/views/orderManagement/defectOrder/property/detailForm";
import normalForm from "@/views/orderManagement/normalMaintenance/detailForm";
import overhaulForm from "@/views/orderManagement/overhaul/detailForm";

import {
  getDetailsApi, //获取详情
  deleteApi,
  saveOrUpdate
} from "@/api/orderManagement/orderChange";
export default {
  components: {
    workorder,
    dispatch,
    defectForm,
    normalForm,
    overhaulForm
  },
  data() {
    return {
      pageType: "",
      status: "",
      orderStatus: ["DRAFT", "DONE"],
      selectOrder: {},
      userInput: false,
      showMore: false,
      showInput: false,
      // showDispatch: false,
      disabled: false,
      showWorkOrder: false,
      orderTitle: "",
      orderType: "",
      orderId: "",
      oldMajor:null,
      formData: {},
      dispatchChangeData: {},
      activeNames: ["1", "2", "3"],
      editFormConfig: {
        itemArr: [
          {
            type: "text",
            label: "工单:",
            prop: "orderCode",
            placeholder: "请选择工单",
            required: true,
            span: 6
          },
          {
            type: "select",
            label: "工单类型:",
            prop: "orderType",
            selectOption: this.$store.getters["dirtData"]("order_type"),
            formatter: val => {
              return this.$store.getters["fineDirtDataName"]("order_type", val);
            },
            disabled: true,
            span: 6
          },
          {
            type: "select",
            label: "专业",
            prop: "newMajor",
            //required: true,
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            span: 6,
          },
          {
            label: "变更原因:",
            prop: "reason",
            type: "textarea",
            maxlength: "500",
            required: true,
            methods: obj => {},
            span: 24,
            rows: 7
          }
        ]
      }
    };
  },
  computed: {
    // 配置进度
    stepConfig() {
      let step = this.orderStatus.indexOf(this.status);
      let obj = {
        nowStep: parseInt(step), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "已完成"]
      };
      return obj;
    },
    // 配置进度右边按钮
    rightBtnArr() {
      let arr = [
        {
          text: "提交",
          icon: "el-icon-position",
          hide: ["DONE", "DEPRECATED"].includes(this.status),
          methods: () => {
            this.doSubmit("submit");
          },
          content: this.$store.getters["isBtnAuth"]("edit")
            ? null
            : "未授权此功能！",
          disabled: !this.$store.getters["isBtnAuth"]("edit")
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide: ["DONE", "DEPRECATED"].includes(this.status),
          methods: () => {
            this.doSubmit("save");
          },
          content: this.$store.getters["isBtnAuth"]("edit")
            ? null
            : "未授权此功能！",
          disabled: !this.$store.getters["isBtnAuth"]("edit")
        },
        {
          text: "删除",
          icon: "el-icon-delete",
          hide: this.status != "DRAFT",
          methods: () => {
            this.deleteData();
          },
          content: this.$store.getters["isBtnAuth"]("delete")
            ? null
            : "未授权此功能！",
          disabled: !this.$store.getters["isBtnAuth"]("delete")
        }
      ];
      return arr;
    },
    // 更多按钮配置
    moreBtnArr() {
      let arr = [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          }
        }
      ];
      return arr;
    },
    showBaseBtn() {
      if (
        ["DRAFT", "", null, undefined].includes(this.status) &&
        this.pageType != "details"
      ) {
        return true;
      } else {
        return false;
      }
    },
    //是否展示正常维护、试验工单、计划性检修工单的基本信息
    showNormal() {
      return ["maintain", "experiment", "repair"].includes(this.orderType);
    },
    //是否获取上面变更的派工信息
    isGetInfo() {
      return (
        ["add", "orderAddChange"].includes(this.pageType) ||
        this.status == "DONE"
      );
    },
    showDispatch() {
      return this.orderType;
    }
  },
  watch: {
    status: {
      handler(val) {
        if (val == "") {
          this.showMore = false;
        } else {
          this.showMore = true;
        }
        if (
          ["DONE", "DEPRECATED"].includes(val) ||
          this.pageType == "details"
        ) {
          this.disabled = true;
          // this.editFormConfig.itemArr.map(i => (i.disabled = true));
        }
      }
    }
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let { id, pageType } = this.$route.query;
      this.pageType = pageType;
      if (id) {
        this.showInput = false;
        this.formData.id = this.$route.query.id;
        //判断页面类型
        let haveJurisdiction = this.$store.getters["isBtnAuth"]("edit");
        this.pageType = haveJurisdiction ? "edit" : "details";

        this.getDetails(id);
      } else {
        this.showInput = true;
        if (this.pageType == "orderAddChange") {
          let { orderId, orderType, orderCode,major } = this.$route.query;
          this.selectOrder = {
            orderType,
            id: orderId
          };
          this.orderType = orderType;
          this.orderCode = orderCode;
          this.orderId = orderId;
          
          this.formData = {
            orderId,
            orderCode,
            orderType
          };
          this.$nextTick(() => {
            this.$refs.basicForm.setFormItem("newMajor", major);
            this.$refs.basicForm.setFormItem("oldMajor", major);
            this.getInfoData(orderType, orderId);
          });
        }
      }
    },
    selectOrders() {
      this.showWorkOrder = false;
      let data = this.$refs.defectOrders.getSelectData();
      let { id, code, orderType, major } = data;
      this.selectOrder = data;
      this.orderType = orderType;
      this.orderId = id;
      this.$nextTick(() => {
        this.getInfoData(orderType, id);
      });
      this.$refs.basicForm.setFormItem("orderCode", code);
      this.$refs.basicForm.setFormItem("orderId", id);
      this.$refs.basicForm.setFormItem("newMajor", major);
      this.$refs.basicForm.setFormItem("oldMajor", major);
      // 设置工单类型
      this.$refs.basicForm.setFormItem("orderType", orderType);
    },
    getInfoData(type, orderId) {
      if (["defect", "overhaul"].includes(type)) {
        this.$refs[type].getDetails(orderId);
      } else {
        this.$refs.normal.getDetails(orderId);
      }
    },
    getDetails(id) {
      id = id || this.formData.id;
      getDetailsApi(id).then(res => {
        let data = res.data;
        let { orderId, orderType, title, status } = data;
        this.oldMajor = data.oldMajor;
        /* 选中的工单，用于派工信息的查询 */
        this.selectOrder = {
          orderType,
          id: orderId
        };
        let changeData = {};
        if (orderType == "defect") {
          //缺陷工单
          changeData = data.defectDispatchVo;
        } else if (orderType == "overhaul") {
          //大修工单
          changeData = data.overhaulDispatchVo;
        } else {
          //正常维护、试验工单、计划检修工单
          changeData = data.orderDispatchVo;
        }
        this.dispatchChangeData = changeData;
        this.formData = data;
        this.orderTitle = title;
        this.orderId = orderId;
        this.orderType = orderType;
        this.status = status;
        this.changeForm();
        this.$nextTick(() => {
          this.getInfoData(orderType, orderId);
        });
      });
    },
    changeForm() {
      this.editFormConfig.itemArr.map(i => {
        if (
          !["DRAFT", undefined, null].includes(this.status) ||
          this.pageType == "details"
        ) {
          i.disabled = true;
        } else {
          if (!["orderType", "orderCode"].includes(i.prop)) {
            i.disabled = false;
          }
        }
      });
    },
    async doSubmit(type) {
      let data = await this.$refs.basicForm.getFormData();
      let dispatchData = await this.$refs.dispatch.getDispatchData();
      if (this.orderType == "defect") {
        data.defectDispatchVo = dispatchData;
        data.overhaulDispatchVo = {};
        data.orderDispatchVo = {};
      } else if (this.orderType == "overhaul") {
        data.defectDispatchVo = {};
        data.overhaulDispatchVo = dispatchData;
        data.orderDispatchVo = {};
      } else {
        data.defectDispatchVo = {};
        data.overhaulDispatchVo = {};
        data.orderDispatchVo = dispatchData;
      }
      data.isCommit = type == "submit" ? true : false;

      data.title = this.orderTitle;
      if (data.title) {
        saveOrUpdate(data).then(res => {
          let data = res.data;
          this.formData = res.data;
          this.$utils.updateStorage();
          this.$message.success("操作成功！");
          if (["add", "orderAddChange"].includes(this.pageType)) {
            this.pageType = "edit";
            this.changeRouter(type);
            if (type == "submit") {
              this.$utils.addOperateLog(
                this.formData.id,
                "新增并提交-工单变更"
              );
            } else {
              this.$utils.addOperateLog(this.formData.id, "新增-工单变更");
            }
          } else {
            this.getDetails(data.id);
            this.$utils.addOperateLog(this.formData.id, "修改-工单变更");
          }      
        });
      } else {
        this.$message.warning("标题不能为空");
      }
    },
    changeRouter(type) {
      /* 修改路由参数 */
      //let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      let obj = {
        id: this.formData.id,
        pageType: "edit",
        status: type == "submit" ? "DONE" : "DRAFT"
      };
      this.$router.push({
        query: obj
      });
    },
    setDispatchData(data) {
      this.dispatchData = data;
    },
    changeData() {
      let arr = this.orderStatus;
      let location = arr.indexOf(this.status);
      this.formData.status = arr[location + 1];
      this.status = arr[location + 1];
    },
    //失去焦点
    loseFocus() {
      if (this.orderTitle != "") {
        this.showInput = false;
      } else {
        this.$message.warning("标题不能为空");
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //删除
    deleteData() {
      //对数据来源进行判断
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteApi(this.formData.id).then(res => {
            this.$utils.updateStorage();
            this.$message.success("操作成功");
            this.$refs.editPage.closePage(300);
          });
        })
        .catch(e => {});
    },
    //用户输入工单标题
    userInputTitle(val) {
      if (val) {
        this.userInput = true;
      } else {
        this.userInput = false;
      }
    },
    //显示工单详情
    goToDetails() {
      if (this.orderId) {
        let form = {
          pageType: "ditails",
          id: this.orderId,
          status: "WAIT_EXECUTE"
        };
        let routerName = "";
        switch (this.orderType) {
          case "defect":
            routerName = "defectOrderDetails";
            break; //缺陷工单
          case "overhaul":
            routerName = "overhaulDetails";
            break; //大修工单
          case "maintain":
            routerName = "normalMaintenanceDetails";
            break; //正常维护
          case "experiment":
            routerName = "experimentOrderDetails";
            break; //试验工单
          case "repair":
            routerName = "planRepairDetails";
            break; //计划检修工单
        }
        let { href } = this.$router.resolve({
          name: routerName,
          query: form
        });
        window.open(href, "_blank");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.orderChangeDetails {
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .titleText {
    display: inline-block;
    height: 30px;
    max-width: 800px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-right: 5px;
  }
  .el-link {
    margin-bottom: 5px;
  }

  .input-link /deep/.el-input__inner {
    cursor: pointer;
    color: royalblue;
  }
  .orderTitle {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
    .remindColor {
      /deep/.el-input__inner {
        border: 1px solid red !important;
      }
    }

    // /deep/.el-input__inner {
    //   border: none;
    //   font-size: 16px;
    //   font-weight: bolder;
    // }
    // /deep/.el-input.is-disabled .el-input__inner,
    // /deep/.el-range-editor.is-disabled input,
    // /deep/.el-textarea.is-disabled .el-textarea__inner {
    //   background-color: rgba(252, 252, 252, 0);
    // }
  }
}
</style>